import { store } from "./redux/store"
import { realm, schemaName } from "./utils/schema"
import { formatFriendMsg, formatGroupMsg } from "./utils/formatFriendMsg"
import { asyncGetFriendList, asyncGetFriendMsg, asyncGetUserInfo, asyncGetGroupList } from "./redux/features/appSlice"
import Realm from "realm"
import httpApi from "./api"
import SplashScreen from 'react-native-splash-screen';


const fromLocalStorages = async (dispatch) => {
    try {
        const UserInfo = realm.objects(schemaName.UserInfo)[0]
        if (UserInfo) {

            dispatch({ type: 'app/SetUserInfo', payload: JSON.parse(JSON.stringify(UserInfo)) })
            dispatch({ type: 'app/SetToken', payload: JSON.parse(JSON.stringify(UserInfo.Token)) })
            //钱包
            const WalletList = realm.objects(schemaName.WalletList).filtered(`state == 1`)
            dispatch({ type: 'wallet/SetWalletList', payload: JSON.parse(JSON.stringify(WalletList)) })

            const Wallet = JSON.parse(JSON.stringify(realm.objects(schemaName.CurrentWalle).filtered(`state == 1`)[0]))
            dispatch({ type: 'wallet/SetWallet', payload: Wallet })
            //用户信息
            const UserInfoList = realm.objects(schemaName.UserInfoList)
            dispatch({ type: 'app/SetUserInfoList', payload: JSON.parse(JSON.stringify(UserInfoList)) })
            let FriendList = realm.objects(schemaName.FriendList).filtered(`UserId == ${UserInfo.Id}`)
            dispatch({ type: 'app/SetFriendList', payload: JSON.parse(JSON.stringify(FriendList)) })
            let GroupList = realm.objects(schemaName.GroupList).filtered(`UserId == ${UserInfo.Id}`)
            dispatch({ type: 'app/SetGroupList', payload: JSON.parse(JSON.stringify(GroupList)) })

            //聊天记录初始化
            dispatch({ type: 'app/SetFriendMsg', payload: formatFriendMsg() })  //未读处理
            dispatch({ type: 'app/SetGroupMsg', payload: formatGroupMsg() }) //未读处理

            dispatch({ type: 'wallet/SetIsWallet', payload: true })
            SplashScreen.hide()
        }
    } catch (error) {

    }
    SplashScreen.hide()
}

const asyncFromLocalStorages = async (dispatch, getState) => {
    try {
        const { userInfo } = getState().app
        if (userInfo.Id) {
            //异步获取新消息
            const getFriendList = await asyncGetFriendList(userInfo.Id)(dispatch)
            const getGroupList = await asyncGetGroupList(userInfo.Id)(dispatch)
            asyncGetUserInfo()(dispatch)

            let MsgSeq = realm.objects(schemaName.FriendMsgSeq).filtered(`UserId == ${userInfo.Id}`)[0]
            const Msg = await asyncGetFriendMsg(Math.max(getFriendList.CurSeq, MsgSeq?.Cur || 0), getFriendList.TotalSeq)(dispatch)
            realm.write(() => {
                for (let index = 0; index < Msg.length; index++) {
                    const element = Msg[index];
                    if ([45].indexOf(element.MT) !== -1) return
                    realm.create(schemaName.FriendMsgLis, { ...element, _id: new Realm.BSON.UUID(), UserId: userInfo.Id }, true);
                }
                realm.create(schemaName.FriendMsgSeq, { Cur: getFriendList.TotalSeq, Total: getFriendList.TotalSeq, UserId: userInfo.Id }, true);
                httpApi.setFriendSeq({ seq: Math.max(getFriendList.CurSeq, MsgSeq?.Cur || 0) - 20 })
            })
            dispatch({ type: 'app/SetFriendMsg', payload: formatFriendMsg() })//未读处理


            let groupListMsg = []
            for (let index = 0; index < getGroupList.length; index++) {
                const element = getGroupList[index];
                let GroupMsgSeq = realm.objects(schemaName.GroupMsgSeq).filtered(`G ==${element.G} and UserId == ${userInfo.Id}`)[0]
                if ((GroupMsgSeq?.Cur || 0) !== element.U) {
                    const res = await httpApi.getGroupMsg({ groupId: element.G, seq: Math.max(element.S, GroupMsgSeq?.Cur || 0), num: element.U })
                    groupListMsg = groupListMsg.concat(res.data.Msgs || [])
                    realm.write(async () => {
                        httpApi.setGroupSeq({ groupId: element.G, seq: Math.max(element.S, GroupMsgSeq?.Cur || 0) - 20 })
                        realm.create(schemaName.GroupMsgSeq, { G: element.G, Cur: element.U, Total: element.U, UserId: userInfo.Id }, true);
                        for (let index = 0; index < res.data.Msgs?.length; index++) {
                            const item = res.data.Msgs[index];
                            realm.create(schemaName.GroupMsgLis, { ...item, G: element.G, _id: new Realm.BSON.UUID(), UserId: userInfo.Id }, true)
                        }
                    })
                }

            }
            dispatch({ type: 'app/SetGroupMsg', payload: formatGroupMsg() }) //未读处理
        }
    } catch (error) {

    }
}



export const loadFromLocalStorages = (isOadFromLocalStorages = true) => {
    store.dispatch(fromLocalStorages)
    if (isOadFromLocalStorages) {
        asyncLoadFromLocalStorages()
    }
}

export const asyncLoadFromLocalStorages = () => {
    store.dispatch(asyncFromLocalStorages)
}
